# -*- coding: utf-8 -*-
# Author   : ZhangQing
# Time     : 2025-08-05 23:29
# File     : user.py
# Project  : codebuddy_craft
# Desc     :
# backend/schemas/user.py
"""
用户数据模式定义 👤

定义用户相关的请求和响应数据结构
"""

from pydantic import BaseModel, Field, EmailStr, validator
from typing import Optional, Dict, Any
from datetime import datetime


class UserUpdateRequest(BaseModel):
    """用户更新请求模型 ✏️"""
    full_name: Optional[str] = Field(None, max_length=100, description="全名")
    email: Optional[EmailStr] = Field(None, description="邮箱地址")
    avatar_url: Optional[str] = Field(None, max_length=255, description="头像URL")
    preferences: Optional[Dict[str, Any]] = Field(None, description="用户偏好")

    @validator('full_name')
    def validate_full_name(cls, v):
        """验证全名"""
        if v:
            return v.strip()
        return v

    @validator('avatar_url')
    def validate_avatar_url(cls, v):
        """验证头像URL"""
        if v:
            import re
            url_pattern = r'^https?://.*\.(jpg|jpeg|png|gif|webp)$'
            if not re.match(url_pattern, v, re.IGNORECASE):
                raise ValueError('头像URL格式不正确')
        return v


class UserSearchResponse(BaseModel):
    """用户搜索响应模型 🔍"""
    id: str = Field(..., description="用户ID")
    username: str = Field(..., description="用户名")
    full_name: Optional[str] = Field(None, description="全名")
    avatar_url: Optional[str] = Field(None, description="头像URL")
    is_verified: bool = Field(..., description="是否已验证")

    class Config:
        from_attributes = True


class UserProfileResponse(BaseModel):
    """用户资料响应模型 📋"""
    id: str = Field(..., description="用户ID")
    username: str = Field(..., description="用户名")
    email: str = Field(..., description="邮箱地址")
    full_name: Optional[str] = Field(None, description="全名")
    avatar_url: Optional[str] = Field(None, description="头像URL")
    is_active: bool = Field(..., description="是否激活")
    is_verified: bool = Field(..., description="是否已验证")
    preferences: Dict[str, Any] = Field(default_factory=dict, description="用户偏好")
    created_at: Optional[datetime] = Field(None, description="创建时间")
    last_login_at: Optional[datetime] = Field(None, description="最后登录时间")

    # 统计信息
    project_count: Optional[int] = Field(None, description="项目数量")
    total_lines: Optional[int] = Field(None, description="总代码行数")

    class Config:
        from_attributes = True
        json_encoders = {
            datetime: lambda v: v.isoformat() if v else None
        }
